
<template>
  <div class='user'>
    <div class="set-btn">
      <el-button type="primary" @click="handelDialogVisible">
        {{ $t('button.wAddSystemUser') }}
      </el-button>
    </div>
    <div class="table-item">
      <!-- slice 说明:
        截取所选的内容 转成新的数组
          slice(参数1，参数2)
          参数1：从哪个下表开始
          参数2：从哪个下标结束
          思路：参数1让页面 * 0 从第一条开始显示，然后 让页码 * 条数 得出全部
      -->
      <el-table
        :data="state.sysUsers.slice((state.currentPage - 1) * state.pageSizes, state.currentPage * state.pageSizes)"
        border style="width: 100%">
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="roleName" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch @change="handelStatusChange(scope.row.id, scope.row.status)" v-model="scope.row.status"
              active-color="green" inactive-color="red"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button type="text" size="small" @click="handelSetRole(scope.row.id)">{{
              $t('button.wempower')
            }}</el-button>
            <el-button type="text" size="small" @click="handelResetPassword(scope.row.id)">{{
              $t('button.wresetPassWord')
            }}</el-button>
            <el-button type="text" size="small" @click="handelDialogVisible(scope.row)">{{
              $t('button.wedit')
            }}</el-button>
            <el-button type="text" size="small" @click="handelDelSysUser(scope.row.id)">{{
              $t('button.wdelete')
            }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination background layout="total,sizes,jumper,prev, pager, next" :total="state.sysUsers.length"
        :current-page="state.currentPage" :page-sizes="[5, 10, 20, 50, 100]" @current-change="handelCurrentChange"
        @size-change="handelSizesChange" />
    </div>
  </div>

  <!-- 添加和编辑 弹出框 -->
  <el-dialog v-model="state.UserDialogVisible" :title="state.dialogVisibleTitle" width="30%"
    :before-close="() => { state.UserDialogVisible = false }">
    <div class="contenr">
      <el-form label-position="top" label-width="100px" :rules="state.rules" :model="state.addSysUserInfo"
        style="max-width: 460px">
        <el-form-item :label="$t('menus.wUserName')" prop="username">
          <el-input v-model="state.addSysUserInfo.username" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="() => { state.addSysUserInfo.username = '' }">重置</el-button>
        <el-button type="primary" @click="handelAddSysUser">
          {{ state.dialogVisibleTitle == '新增系统用户' ? '添加' : '编辑' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 角色授权 -->
  <el-dialog v-model="state.RoleDialogVisible" title="角色授权" width="30%"
    :before-close="() => { state.RoleDialogVisible = false }">
    <el-select @change="handelRolesChange" :value="state.rolesValue" class="m-2" placeholder="选择角色" size="large">
      <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
    </el-select>
  </el-dialog>
</template>

<script setup lang='ts'>
import { onMounted, reactive, Ref, ref } from 'vue'
import 'element-plus/es/components/message/style/css'
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// api 
import {
  // 添加用户
  addSysUser,
  // 删除用户
  deleteSysUsers,
  // 获取系统用户列表
  getAllSysUsers,
  // 修改状态
  updateStatus,
  // 编辑用户信息
  updateSysUser,
  // 重置密码
  resetPassword,
  // 设置角色
  setRole
} from '@/api/system/user'
import { ElMessage } from 'element-plus';
import { getAllRoles } from '@/api/system/role'
// 添加断言
const { proxy } = getCurrentInstance() as ComponentInternalInstance

// 属性
const state = reactive({
  // 系统用户列表
  sysUsers: [],
  // 页码
  currentPage: 1,
  // 条数
  pageSizes: 5,
  // 控制 添加用户的 弹窗
  UserDialogVisible: false,
  // 控制 角色授权的 弹窗
  RoleDialogVisible: false,
  // 弹窗框 的 标题
  dialogVisibleTitle: '',
  // 点击当前用户的Id
  currentUserId: 0,
  // 授权value
  rolesValue: "123",
  // 用户信息
  addSysUserInfo: {
    // 用户名
    username: '',
  },
  // 验证规则
  rules: {
    username: [
      {
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
      }
    ]
  }
})
// 定义 授权列表 的类型
interface Role {
  id: number,
  name: string,
}
// 授权列表
const roles: Ref<Array<Role> | null> = ref(null)



// 获取系统用户列表
const onGetAllSysUsers = () => {
  getAllSysUsers().then(res => {
    state.sysUsers = res.data
  })
}
// 改变页码数
const handelCurrentChange = (val: number) => {
  state.currentPage = val
}
// 改变当前条数
const handelSizesChange = (val: number) => {
  state.pageSizes = val
}
// 用户的增删改查
// 打开 添加用户 弹窗
const handelDialogVisible = (user: any) => {
  state.UserDialogVisible = true
  if (user.username) {
    state.dialogVisibleTitle = '编辑系统用户'
    state.addSysUserInfo.username = user.username
  } else {
    state.dialogVisibleTitle = '新增系统用户'
  }
}
// 添加 用户
const handelAddSysUser = () => {
  if (state.dialogVisibleTitle == '新增系统用户') {
    // 添加用户
    addSysUser(state.addSysUserInfo).then(res => {
      if (res.data === 1) {
        state.UserDialogVisible = false
        ElMessage({
          message: '添加成功！',
          type: 'success',
        })
        onGetAllSysUsers()
      } else if (res === undefined) {
        ElMessage.error('用户名已存在！')
      }
    })
  } else {
    // 编辑用户
    updateSysUser(state.addSysUserInfo).then(res => {
      if (res.data === 0) {
        ElMessage({
          message: '修改成功！',
          type: 'success',
        })
        onGetAllSysUsers()
        state.UserDialogVisible = false
      } else if (res === undefined) {
        ElMessage.error('用户名已存在！')
      }
    })
  }

}
// 删除用户
const handelDelSysUser = (id: number) => {
  deleteSysUsers(id).then(res => {
    if (res.data === 1) {
      ElMessage({
        message: '删除成功！',
        type: 'success',
      })
      onGetAllSysUsers()
    }
  })
}
// 修改用户状态
const handelStatusChange = (Id: number, status: boolean) => {
  updateStatus(Id, status).then(res => {
    onGetAllSysUsers()
  })
}
// 重置密码
const handelResetPassword = (Id: number) => {
  proxy?.$confirm('重置该用户密码，请谨慎操作！').then(() => {
    resetPassword(Id).then(res => {
      proxy?.$Notify.success('密码已经重置成功')
    })
  })

}
// 角色授权
const handelSetRole = (userId: number) => {
  // 获取权限列表
  getAllRoles().then(res => {
    roles.value = res.data
    state.RoleDialogVisible = true
    state.currentUserId = userId
  })
}
// 监听角色选择
const handelRolesChange = (roleId: number) => {
  setRole(state.currentUserId, roleId).then(res => {
    if (res.data === 1) {
      proxy?.$Notify.success('切换成功')
    }
  })
}
onMounted(() => {
  onGetAllSysUsers()
})
</script>

<style lang='less' scoped>
.pagination {
  margin-top: 20px;
  float: right;
}

.set-btn {
  margin-bottom: 20px;
}
</style>